package com.gxpt.app.view;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseActivity;
import com.gxpt.app.Constant;
import com.gxpt.app.MessageEvent;
import com.gxpt.app.R;
import com.gxpt.app.adapter.city_sub_Adapter;
import com.gxpt.app.bean.getregion_bean;
import com.utils.T;
import com.utils.logger.Logger;
import com.utils.okhttputils.HttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * Created by dufeng on 2017/8/4.
 */

@ContentView(R.layout.activity_city_select_2_str)
public class Activity_city_select_2_str extends BaseActivity {

    @ViewInject(R.id.toback)
    Button toback;

    @ViewInject(R.id.txt_strs)
    TextView txt_strs;

    @ViewInject(R.id.txt_ids)
    TextView txt_ids;

    @ViewInject(R.id.txt_title)
    TextView txt_title;

    @ViewInject(R.id.txt_right)
    TextView txt_right;

    @ViewInject(R.id.type_main)
    LinearLayout type_main;
//
    @ViewInject(R.id.recycler_sub)
    RecyclerView recycler_sub;

    String main_id="";
    String main_name="";
    city_sub_Adapter mCity_sub_Adapter;
    List<getregion_bean.getregion> data_sub = new ArrayList<getregion_bean.getregion>();



    List<String> strs = new ArrayList<String>();
    List<String> ids = new ArrayList<String>();
    String formData="";
    String formData_id="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle b = getIntent().getBundleExtra("DATA");
        if(b!=null){
            formData = b.getString("strs");
            formData_id = b.getString("ids");
            if(formData !=null){
                String[] arr = formData.split(",");
                for (String s : arr)
                {
                    s.trim();
                    if(!s.equals("")){
                        strs.add(s);
                    }

                }
            }

            if(formData_id !=null){
                String[] arr = formData_id.split(",");
                for (String s : arr)
                {
                    s.trim();
                    if(!s.equals("")){
                        ids.add(s);
                    }
                }
            }
        }
        x.view().inject(this);
        initView();
        initData();
    }

    @Override
    public void initView() {
        txt_title.setText(getString(R.string.txt_city_select));
        txt_right.setVisibility(View.VISIBLE);

        if(!formData.isEmpty()){
            txt_strs.setText(formData);
            txt_ids.setText(formData_id);
        }
        // 设置布局管理器
        LinearLayoutManager linearLayoutManager_sub = new LinearLayoutManager(this);
        linearLayoutManager_sub.setOrientation(LinearLayoutManager.VERTICAL);
        recycler_sub.setLayoutManager(linearLayoutManager_sub);

        // 设置适配器
        mCity_sub_Adapter = new city_sub_Adapter(context,data_sub);
        recycler_sub.setAdapter(mCity_sub_Adapter);
//        recycler_sub.addItemDecoration(new MyDecoration(context, MyDecoration.VERTICAL_LIST));
        mCity_sub_Adapter.setOnItemClickListener(new city_sub_Adapter.MyItemClickListener() {

            @Override
            public void onItemClick(View view, int postion) {
//
                txt_strs.setText("");
                txt_ids .setText("");
                TextView list_title = (TextView) view.findViewById(R.id.list_title);
                TextView list_id = (TextView) view.findViewById(R.id.list_id);


                boolean isAdd = true;
                if(strs.size()!=0){
                    for(int a=0;a < strs.size();a++){
                        if(strs.get(a).equals(list_title.getText().toString())){
                            isAdd = false;
                            strs.remove(a);
                            ids.remove(a);
                            break;
                        }else{
                            isAdd = true;
                        }
                    }
                }

                if(isAdd){
                    strs.add(list_title.getText().toString());
                    ids.add(list_id.getText().toString());
                }

                StringBuffer uu = new StringBuffer();
                StringBuffer ww = new StringBuffer();
                for(String str:strs){
                    uu.append(str+",");
                }
                for(String str:ids){
                    ww.append(str+",");
                }
                if(uu.length()>0){
                    uu.deleteCharAt(uu.length()-1);
                }
                if(ww.length()>0){
                    ww.deleteCharAt(ww.length()-1);
                }

                txt_strs.setText(uu.toString());
                txt_ids .setText(ww.toString());


            }
        });
    }

    @Override
    public void initData() {
        toNet_getregion();
    }


    @Event(value={R.id.toback,R.id.txt_right})
    private void getEvent(View view){
        switch(view.getId()){
            case R.id.toback:
                closeActivity();
                break;
            case R.id.txt_right:
                EventBus.getDefault().post(new MessageEvent(
                        Constant.ACTION_city_str_sel,
                        txt_strs.getText().toString(),
                        txt_ids.getText().toString()));
                finish();
                break;
        }
    }



    private void init_List_main_type(List<getregion_bean.getregion> d){

        if(d == null)   return;
        if(d.size()<=0) return;

        type_main.removeAllViews();

        for (int a = 0; a < d.size(); a++) {
            type_main.addView(creatListItemView(d.get(a), d.get(a).id));


        }
        //设置第一个默认选中
        RelativeLayout typelayout = (RelativeLayout)type_main.getChildAt(0).findViewById(R.id.typelayout);
        typelayout.setBackgroundColor(getResources().getColor(R.color.button_huise));
    }

    private View creatListItemView(getregion_bean.getregion d, int id) {
        View convertView = LayoutInflater.from(context).inflate(R.layout.item_area_list, null);

        TextView list_title = (TextView)convertView.findViewById(R.id.list_title);
        list_title.setText(d.name);

        convertView.setId(id);
        convertView.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                int ViewID = v.getId();

                RelativeLayout typelayout = (RelativeLayout)v.findViewById(R.id.typelayout);
                typelayout.setBackgroundColor(getResources().getColor(R.color.button_huise));

                TextView list_title = (TextView)v.findViewById(R.id.list_title);

                for(int a=0;a<type_main.getChildCount();a++){
                    if(type_main.getChildAt(a).getId()!=ViewID){
                        RelativeLayout aa = (RelativeLayout)type_main.getChildAt(a).findViewById(R.id.typelayout);
                        aa.setBackgroundColor(getResources().getColor(R.color.white));
                    }
                }

                main_id   = ""+ViewID;
                main_name = ""+list_title.getText().toString();
                toNet_getregion();
            }
        });
        return convertView;
    }



    //////NET DO
    StringCallback do_getregion = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
//            Logger.e(s);
            try{
                getregion_bean data = new Gson().fromJson(s, getregion_bean.class);

                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    if(data.data != null){
                        if(data.data.size()>0){
                            //
                            if(main_id.isEmpty()){
                                init_List_main_type(data.data);
                            }else{
                                data_sub = data.data;
                                mCity_sub_Adapter.addItem(data_sub);
                            }

                            main_id   = ""+data.data.get(0).id;
                            main_name = ""+data.data.get(0).name;
                            toNet_getregion();
                        }
                    }

                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };
    /////NET
    private void toNet_getregion(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "category");
            jsonBody.put("serviceName",          "getregion");

            jsonBody.put("sub_id",                ""+main_id);

        } catch (JSONException e) {
            e.printStackTrace();
        }
//        Logger.i(jsonBody.toString()+" ==["+Constant.URL_register+" ]");
        HttpUtils.http_post_string(Constant.URL_getregion,jsonBody.toString(),do_getregion);
    }



























}
